package com.smarthome.ipc.hk.task;

import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.smarthome.common.tools.IPNetUtils;
import com.smarthome.domain.ipc.IpcConstants;
import com.smarthome.domain.ipc.req.HKIpcResidenceDoorStatusRequest;
import com.smarthome.ipc.IpcClientMain;
import com.smarthome.ipc.command.HkNetDvrInit;
import com.smarthome.ipc.hk.demo.HCNetSDK;
import com.smarthome.ipc.hk.entity.NetDvrLoginV30Entity;

/**
 * 获取门口机状态
 * 
 * @author add by denghw 2015/10/09
 *
 */
@Service
public class HKWorkStateTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(HKWorkStateTask.class);
    private final static String PRE_LOGGER = "[HKWorkStateTask]";

    @Resource(name = IpcConstants.IPC_COMMAND_RESIDENCE_DOOR_INIT_HK)
    private HkNetDvrInit hkNetDvrInit;// service

    @Scheduled(initialDelay = 30 * 1000, fixedRate = 2 * 60 * 60 * 1000)
    public void getHkdoorsState() {
        HKIpcResidenceDoorStatusRequest request = new HKIpcResidenceDoorStatusRequest();
        request.setCommand(IpcConstants.IPC_COMMAND_RESIDENCE_DOOR_HK_STATUS);
        request.setIpcId(IPNetUtils.getLocalMac());

        // 1.获取小区内所有的门口机
        Map<String, Object> hkdoors = hkNetDvrInit.getLocalCache();
        // 2.向云后台服务器推送状态信息
        for (String doorkey : hkdoors.keySet()) {
            NetDvrLoginV30Entity doorObj = (NetDvrLoginV30Entity) hkdoors.get(doorkey);
            HCNetSDK.NET_DVR_WORKSTATE_V30 workState = doorObj.getM_strWorkState();
            if (workState == null) {
                hkNetDvrInit.rtnBackErrMsg(request.getDeviceId(), request.getCommand(), String.valueOf(doorObj.gethCNetSDK().NET_DVR_GetLastError()), "获取设备状态失败");
                continue;
            }
            if (workState.dwDeviceStatic == 0 && workState.dwLocalDisplay == 0) {
                request.setStatus("0");
            } else {
                request.setStatus(String.valueOf(workState.dwDeviceStatic));
            }
            try {
                IpcClientMain.getInstance().sendCommand(request);
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                LOGGER.info(PRE_LOGGER + "海康门口机控制器获取门口机状态后，向云平台推送状态信息产生异常！" + e1.getMessage() + ",门口机信息:[" + JSONObject.toJSONString(request) + "].");
            }

        }
    }

}
